package com.qipa.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.qipa.common.ResultModel;
import com.qipa.netty.service.HandlerService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
@Slf4j
public class HealthServerHandler extends ChannelInboundHandlerAdapter {


    private final String wsUri;
    @Autowired
    HandlerService handlerService;


    public HealthServerHandler() {
        this.wsUri = "/ws";
    }
    public HealthServerHandler(String wsUri) {
        this.wsUri = wsUri;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //客户端连接会来这里
        log.info("HealthServerHandler.channelActive 客户端[{}]连接过来", ctx.channel().localAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//        logger.info("有客户端关闭连接");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        if (msg instanceof TextWebSocketFrame) {
            //TextWebSocketFrame
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
            log.info(textWebSocketFrame.text());

        } else if (msg instanceof FullHttpRequest) {
            //http请求
            FullHttpResponse response = null;
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;

            if (wsUri.equalsIgnoreCase(fullHttpRequest.uri())) {
                //websocket进来，连接socket，因为连接socket其实是http协议
                //如果是WebSocket请求，则保留数据并传递到下一个ChannelHandler
                ctx.fireChannelRead(fullHttpRequest.retain());
            } else {
                FullHttpRequest req = (FullHttpRequest) msg;//客户端的请求对象
                JSONObject responseJson = new JSONObject();//新建一个返回消息的Json对象
                ResultModel resultModel = new ResultModel();
                if (fullHttpRequest.method() == HttpMethod.GET) {

                } else if (fullHttpRequest.method() == HttpMethod.POST) {
                    //post请求
                } else {
                    //非get和非post
                }
            }
        } else if (msg instanceof WebSocketFrame) {
            //如果是Websocket请求，则进行websocket操作
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }


    //处理Websocket的代码
    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        //如果是WebSocket请求，则保留数据并传递到下一个ChannelHandler
        ctx.fireChannelRead(frame.retain());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }


}
